package com.wk.hooker;


import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ToggleButton;

import com.wk.hooker.hooks.HookThread;
import com.wk.hooker.hooks.Hookservice;
import com.wk.hooker.login.R;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;

import java.util.Observable;


public class MainActivity extends Activity implements View.OnClickListener {


    private final static String issaomaopen = "IS_SAOMAOPEN";

    private final static String saomatime = "SAOMA_TIME";

    private final static String qr = "QR";

    private final static String moniqr = "MoNI_QR";

    private final static String weixinNumber = "WeiXinNumber";

    private final static String WeixinBianHao = "BianHao";




    private ActivityManager manager;
    private List<ActivityManager.RunningAppProcessInfo> runningProcesses;
    private String packName;
    private PackageManager pManager;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // upgradeRootPermission(getPackageCodePath());

        SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);

        SharedPreferences wrrite = getSharedPreferences("weixinok2", Context.MODE_WORLD_WRITEABLE);

        ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglebutton);
        toggleButton.setChecked(pref.getBoolean(issaomaopen, true));

        CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
        checkBox.setChecked(pref.getBoolean(moniqr, false));

        EditText editqr = (EditText) findViewById(R.id.edit_qr);
        String sqr = pref.getString(qr, "https://login.weixin.qq.com/l/wY-6rtnKFA==");
        editqr.setText(sqr);

        EditText edittime = (EditText) findViewById(R.id.edit_time);
        String stim = pref.getString(saomatime, "40");
        edittime.setText(stim);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_startweixin).setOnClickListener(this);
        findViewById(R.id.btn_clearmsg).setOnClickListener(this);

        EditText editNumber = (EditText) findViewById(R.id.edit_number);
        editNumber.setText(pref.getString(weixinNumber, null));

        EditText editNumber3 = (EditText) findViewById(R.id.edit_number3);
        editNumber3.setText(pref.getString(WeixinBianHao, null));

        if (isServiceWork(this, "com.wk.hooker.hooks.Hookservice")) {
            Button button = (Button) findViewById(R.id.btn_startweixin);
            if (HookThread.getIntance().isAlive()) {
                button.setText("停止服务（服务已经开启OK）");
            } else {
                button.setText("停止服务（服务已经开启）");
            }
        }
        if (!saveFIleData()) {
            finish();
            return;
        }


    }


    public static boolean upgradeRootPermission(String pkgCodePath) {
        Process process = null;
        DataOutputStream os = null;
        try {
            String cmd="chmod 777 " + pkgCodePath;
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                SharedPreferences pref = getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
                SharedPreferences.Editor edit = pref.edit();
                CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
                edit.putBoolean(moniqr, checkBox.isChecked());
                ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglebutton);
                edit.putBoolean(issaomaopen, toggleButton.isChecked());
                EditText editqr = (EditText) findViewById(R.id.edit_qr);
                edit.putString(qr, editqr.getText().toString());
                EditText edittime = (EditText) findViewById(R.id.edit_time);
                edit.putString(saomatime, edittime.getText().toString());
                EditText editNumber = (EditText) findViewById(R.id.edit_number);
                edit.putString(weixinNumber, editNumber.getText().toString());

                EditText editNumber3 = (EditText) findViewById(R.id.edit_number3);
                edit.putString(WeixinBianHao, editNumber3.getText().toString());
                edit.commit();

                break;
            case R.id.btn_startweixin:
//                Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
//                startActivity(intent);
                if (isServiceWork(this, "com.wk.hooker.hooks.Hookservice")) {
                    Button button = (Button) findViewById(R.id.btn_startweixin);
                    button.setText("开启服务（未开启）");
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, Hookservice.class);
                    stopService(intent);
                } else {
                    Button button = (Button) findViewById(R.id.btn_startweixin);
                    button.setText("停止服务（服务已经开启）");
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, Hookservice.class);
                    startService(intent);
                }

                break;
            case R.id.btn_clearmsg:
                Intent intent = new Intent(MainActivity.this, ClerarWeinXinMsgActivity.class);
                startActivity(intent);
                break;
        }
        pManager = getPackageManager();
        manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        killOthers(this);
    }


    private boolean saveFIleData() {

        byte[] bty = null;

        try {
            InputStream is = getResources().getAssets().open("qr.jpg");
            bty = new byte[is.available()];
            is.read(bty);
            File file = new File(Environment.getExternalStorageDirectory(), "qr.jpg");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fis = new FileOutputStream(file);
            fis.write(bty, 0, bty.length);
            fis.flush();
            fis.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }


        return true;
    }

    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();

            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    public boolean isRunningApp(Context context, String packageName) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {

            String s = info.baseActivity.getClassName();
            if (info.topActivity.getPackageName().equals(packageName) && (s.contains("MainActivity") ||
                    s.contains("GuideActivity") || s.contains("MyFirstActivity"))) {
                isAppRunning = true;
                break;
            } else if (info.topActivity.getPackageName().equals(packageName)) {
                break;
            }
        }
        return isAppRunning;
    }


    /**
     * 杀死其他正在运行的程序
     *
     * @param context
     */
    private void killOthers(Context context) {

        runningProcesses = manager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo runningProcess : runningProcesses) {
            try {
                packName = runningProcess.processName;
                ApplicationInfo applicationInfo = pManager.getPackageInfo(packName, 0).applicationInfo;
                if ("com.tencent.mm".equals(packName)) {
                    forceStopPackage(packName, context);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 强制停止应用程序
     *
     * @param pkgName
     */
    private void forceStopPackage(String pkgName, Context context) throws Exception {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        Method method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
        method.invoke(am, pkgName);
    }

    /**
     * 判断某个应用程序是 不是三方的应用程序
     *
     * @param info
     * @return
     */
    public boolean filterApp(ApplicationInfo info) {
        if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
            return true;
        } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
            return true;
        }
        return false;
    }




}
